import React from 'react'
import { connect } from 'react-redux'
import { Form, Switch, Icon, Row, Col, Button, Radio, message, Alert, Select, Popover, Upload, Modal} from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import config from 'config';
import menuRoute from 'routes/menuRoute';
import {deepCopy, messages} from "share/common";
import { LanguageInput } from 'components/index';
import ListSelector from "components/list-selector";
import TitleAndContentI18n from "components/template/title-and-content-i18n/title-and-content-i18n"
import subApplicationService from 'containers/setting/sub-application/sub-application.service'
import configureStore from "stores";

class EditSubApplicationInfo extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      subApplicationPage: menuRoute.getRouteItem('sub-application-privatization','key'),    //子应用管理的页面项
      loading: false,
      appCode: props.appCode,
      sectionCode: props.params.sectionCode,
      appName: props.params.appName,
      appDesc: props.params.appDesc,
      tenantId: props.company.tenantId,
      record: {
        appCode: null ,
        appDesc: null ,
        appIcon: null,
        appName: null,
         i18n: {} ,
        id: null,
        enabled: true,
         sectionId: null,
        showAll: true ,
        templateWidgetId: null,
        tenantId: null,
         userGroupList: null, 
      },
      warning: true,
      chosenEmployeeIDs:[], //选中的人员组id
      chosenEmployeeNames:[], //选中的人员组names
      showSelectEmployeeGroup: false, //是否展示选择人员组

      id: props.id,
      code: props.code,
      sectionId: props.sectionId,
      employeeValue: 1001,
      uploadedWeChatImages: [],//已经上传的企业微信Logo
      i18n: {title: [], content: []},
      uploadedImages: [],
      visible: false,
      src: "",
    };
  }

  componentWillMount() {
    this.getTenantSubApplicationList();
  }

  //获取子应用详情
  getTenantSubApplicationList = ()=>{
    const {appCode, chosenEmployeeNames, appName, appDesc, tenantId, i18n} = this.state;
    let protocolContent = "";
    let protocolName = "";
     subApplicationService.getTenantSubApplicationList(appCode).then(res => {
      let protocol = res.data.protocol;
      if(protocol){
        i18n.content = protocol.i18n.protocolContent;
        i18n.title = protocol.i18n.protocolName;
      }else{
        res.data.protocol = {
          protocolName: "",
          protocolContent: "",
          i18n: {
            protocolName: [],
            protocolContent: [],
          }
        }
      }
      this.setState({
        i18n: deepCopy(i18n),
      });
      if(res.data.userGroupList && res.data.userGroupList.length){
        res.data.userGroupList.map(item => {
          chosenEmployeeNames.addIfNotExist(item.name)
        });
        this.setState({
          chosenEmployeeNames,
        })
      }
       if(res.data.appIcon) {
         let uploadedImage = [{
           uid: res.data.id ? res.data.id : 1,
           name: 'xx.png',
           status: 'done',
           url: res.data.appIcon ? res.data.appIcon : '',
         }];
         this.setState({
           uploadedImages: uploadedImage,
         });
       }
      res.data.appName = res.data.appName ? res.data.appName : appName;
      res.data.appDesc = res.data.appDesc ? res.data.appDesc : appDesc;
      res.data.tenantId = tenantId;
      res.data.enabled = res.data.enabled === null ? true : res.data.enabled;
      res.data.showAll = res.data.showAll === null ? true : res.data.showAll;
      res.data.userGroupList = res.data.userGroupList === null ? [] : res.data.userGroupList;
      this.setState({
        record: res.data,
        chosenEmployeeIDs: res.data.userGroupList === null ? [] : res.data.userGroupList,
      })
    }).catch(error => {
    });
  };

  handleSave = () => {
    const {record, chosenEmployeeIDs, subApplicationPage, uploadedImages } = this.state;
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            let record = this.state.record;
            if(values.enableProtocol){
              record = this.handleProtocolContent();
              if(!record){
                return;
              }
            }else{
              record.protocol = null;
            }
          this.setState({
            loading: true
          });
          let param = Object.assign(record, values);
            param.appIcon = uploadedImages.length ? (uploadedImages[0].url || uploadedImages[0].response.fileURL) : '';
            chosenEmployeeIDs.map(item => {
            param.userGroupList.push({id: item.id});
          });
           subApplicationService.createNewSubApplication(param).then(res => {
            message.success(messages('budget-setting.key31'/*保存成功！*/));
            this.context.router.replace(subApplicationPage.url);
          })
            .catch(error => {
             message.success(error.response.data.message);
          })
            .finally((final) =>{
            this.setState({ loading: false });
          })
          }
        });
  };


  handleProtocolContent = () => {
    const {record} = this.state;
    let err = 0;
    let reg = (/<\/?.?\/?>/g);
    record.protocol.i18n.protocolName.map(item => {
      if(item.value.length > 100){
        err = 100;
      }
    });
    record.protocol.i18n.protocolContent.map(item => {
      if(item.value.replace(/\s/g,"").length > 500){
        err = 500;
      }
    });

    if(err === 100){
      message.error(messages('setting.key1782')/*名称长度不能超100个字符*/);
    }else if(err === 500){
      message.error(messages('setting.key1783')/*内容长度不能超过500个字符*/)
    }else {
      let err2 = true;
      record.protocol.i18n.protocolName.map(item => {
        if (item.value) {
          if (record.protocol.i18n.protocolContent.filter(con => con.language === item.language)[0].value) {
            err2 = false;
          }
        }
        if (item.language.toLowerCase() === this.props.language.code.toLowerCase()) {
          record.protocol.protocolName = item.value;
          record.protocol.protocolContent = record.protocol.i18n.protocolContent.filter(ans => ans.language === item.language)[0].value
        }
      });
      if (err2) {
        message.error(messages('setting.key1784')/*请至少填写一种语言的标题和正文*/);
      }else{
        return record;
      }
    }
  };

  //选择人员组
  handleShowGroupModal = () => {
    this.refs.chooserGroupBlur.focus();
    this.setState({showSelectEmployeeGroup: true});
  };

  handleSelectEmployeeCancel = () => {
    this.setState({showSelectEmployeeGroup: false})
  };

  //改变人员组设置
  onChangeEmployeeValue = (e) => {
    this.setState({
      employeeValue: e.target.value
    }, () => {
      this.setState({chosenEmployeeIDs: []});
    });
  };


  handleSelectEmployeeOk = (values) => {
    let IDs = [];
    let Names = [];
    values.result.map(item => {
      IDs.push({id: item.id, name: item.name});
      Names.push(item.name);
    });
    this.setState({
      chosenEmployeeIDs: IDs,
      chosenEmployeeNames: Names,
    });
    this.handleSelectEmployeeCancel();
  };

  //子应用名称：多语言
  i18nAppNameChange = (name, i18nName) => {
    const record = this.state.record;
    record.appName = name;
    if (!record.i18n) {
      record.i18n = {};
    }
    record.i18n.appName = i18nName;
  };

  //子应用名称：多语言
  i18nAppDescChange = (name, i18nName) => {
    const record = this.state.record;
    record.appDesc = name;
    if (!record.i18n) {
      record.i18n = {};
    }
    record.i18n.appDesc = i18nName;
  };

  onI18nChange = (i18n) => {
    let record = this.state.record;
    record.protocol.i18n.protocolContent = i18n.content;
    record.protocol.i18n.protocolName = i18n.title;
    this.setState({ record })

  };


  //点击图片放大预览
  handlePreview = (file) => {
    this.setState({
      visible: true,
      src: file.url || file.thumbUrl
    });
  };

  //取消图片放大预览
  handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  //上传汇联易logo图片后的回调函数
  handleUploadImageChange = (fileList) => {
    this.setState({uploadedImages: fileList.fileList});
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { subApplicationPage, record, warning, chosenEmployeeIDs, uploadedImages, visible, src,
      showSelectEmployeeGroup, chosenEmployeeNames, sectionCode, i18n } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 10},
    };
    const upload_headers = {
      'Authorization': 'Bearer ' + configureStore.store.getState().main.authToken.access_token
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">{messages('feedback.key14'/*上传图片*/)}</div>
      </div>
    );
    const message = (
      <div>
        {
          sectionCode === 'VENDOR' && this.props.form.getFieldValue('enabled') ?
          <span>
            {messages('setting.key1495',{arg1:record.appName})/*请确保在供应商管理中{arg1}已开通，否则不能使用*/}。
          </span> : null
        }
        {
          record.appCode === 'MILE_EXPENSE' || record.appCode === 'AGENCY' ?
          <span>{messages('setting.key1510',{arg1:record.appName})/*请确保{arg1}已开通，否则不能使用。*/}</span> : null
        }
        {
          record.appCode === 'INVOICE_BATCH'?
            <span>{messages('setting.key1827',{arg1:record.appName})/*请确保{arg1}已设置，否则不能使用*/}</span> : null
        }
        <span style={{float: 'right', cursor: 'pointer'}} onClick={() => {this.setState({warning: false})}}>X</span>
      </div>
    );
    return (
      <div className="sub-application-info">
        <div>
          <span style={{fontSize: 18, fontWeight: 700, color: '#656565'}}>
            {messages('setting.key1025'/*编辑应用*/)}</span>
        </div>
        {
          warning &&
          (
            (sectionCode === 'VENDOR' && this.props.form.getFieldValue('enabled'))
            || (record.appCode === 'MILE_EXPENSE' || record.appCode === 'AGENCY' || record.appCode === 'INVOICE_BATCH' )
          ) ?
            <Row style={{margin: '30px 0'}}>
              <Col span={16} offset={1}>
                <Alert message={message} type="warning" showIcon/>
              </Col>
            </Row>
            : null
        }
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')/* 状态 */}>
            {getFieldDecorator('enabled', {
              initialValue: record.enabled,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1496')/*应用Logo*/}>
            <Upload
              action={`${config.baseUrl}/api/upload/static/attachment`}
              headers={upload_headers}
              listType="picture-card"
              fileList={uploadedImages}
              accept="image/*"
              data={{attachmentType: 'OTHER'}}
              onPreview={this.handlePreview}
              onChange={this.handleUploadImageChange}>
              {uploadedImages.length >= 1 ? null : uploadButton}
            </Upload>
          </FormItem>
          <FormItem {...formItemLayout}
                    label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('setting.key1026'/*应用名称*/)}</span>}>
            <LanguageInput
              key={1}
              name={record.appName}
              i18nName={record.i18n && record.i18n.appName ? record.i18n.appName : null}
              placeholder={messages('common.please.enter')}
              isEdit={true}
              disabled={sectionCode === 'VENDOR'}
              nameChange={this.i18nAppNameChange}
            />
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1031')/*描述*/}>
            <LanguageInput
              key={2}
              name={record.appDesc}
              i18nName={record.i18n && record.i18n.appDesc ? record.i18n.appDesc : null}
              placeholder={messages('common.please.enter')}
              isEdit={true}
              nameChange={this.i18nAppDescChange}
            />
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1154')/*适用人员*/}>
            {getFieldDecorator('showAll', {
              initialValue: record.showAll,
              rules: [{
                required: true,
                message: messages('setting.key1785')/*请选择适用人员*/
              }]
            })
            (<RadioGroup>
              <Radio value={true}>{messages('setting.key793')/*全部人员*/}</Radio>
              <Radio value={false}>{messages('setting.key794')/*按人员组添加*/}</Radio>
            </RadioGroup>)
            }
          </FormItem>
          {!this.props.form.getFieldValue('showAll') && (
            <Row style={{marginBottom: 24}}>
              <Col span={6} offset={6}>
                <Select placeholder={chosenEmployeeIDs.length ?
                  messages('setting.key1468', {arg1: chosenEmployeeIDs.length}) :
                  messages('common.please.select')}
                        style={{width: 450}}
                        onFocus={this.handleShowGroupModal}
                        dropdownStyle={{display: 'none'}}/>
                <input ref="chooserGroupBlur" style={{position: 'absolute', top: '-9999vh', zIndex: -1}}/>
                <div style={{marginTop: 5}}>
                  {
                    chosenEmployeeNames.map((item, index) => {
                      return ( <span key={index}>{item}&nbsp;&nbsp;</span>)
                    })
                  }
                </div>
              </Col>
            </Row>
          )}
          <FormItem {...formItemLayout} label={<span>{messages('setting.key1610')/*用户协议*/}
            <Popover overlayStyle={{maxWidth: 350}}
                     content={messages('setting.key1786')/*员工在首次打开该应用时，需同意协议后方可使用*/}>
                            &nbsp;<Icon type="question-circle-o" style={{cursor: "pointer", color: "rgba(0,0,0,0.5)"}}/>
                          </Popover>
                        </span>}>
            {getFieldDecorator('enableProtocol', {
              initialValue: record.enableProtocol ? record.enableProtocol : false,
              rules: [{
                required: true,
                message: messages('setting.key1787')/*请选择用户协议*/
              }]
            })
            (<RadioGroup>
              <Radio value={false}>{messages('setting.key1728')/*不启用*/}</Radio>
              <Radio value={true}>{messages('common.status.enable')/*启用*/}</Radio>
            </RadioGroup>)
            }
          </FormItem>
          {
            this.props.form.getFieldValue("enableProtocol") &&
            (
              <FormItem {...formItemLayout} label={<span><span style={{color: "red"}}>*</span>&nbsp;{messages('setting.key1788')/*协议标题及内容*/}</span>}>
                <TitleAndContentI18n i18n={i18n}
                                     contentType={'textArea'}
                                     onI18nChange={this.onI18nChange}/>
              </FormItem>
            )
          }
          <FormItem wrapperCol={{ offset: 6 }}>
            <Row gutter={1}>
              <Col span={3}>
                <Button type="primary"
                        onClick={this.handleSave}
                        loading={this.state.loading}>
                  {messages('common.save')/* 保存 */}
                </Button>
              </Col>
              <Col span={3}>
                <Button onClick={() => {this.context.router.replace(subApplicationPage.url);}}> {messages('setting.key1114')/*返回*/}
                </Button>
              </Col>
            </Row>
          </FormItem>
        </Form>
        <ListSelector
          type="user_group"
          selectedData={chosenEmployeeIDs}
          labelKey="name"
          showDetail={true}
          visible={showSelectEmployeeGroup}
          onOk={this.handleSelectEmployeeOk}
          onCancel={this.handleSelectEmployeeCancel}
        />
        <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
          <img alt="加载失败" style={{ width: '100%' }} src={src} />
        </Modal>
      </div>
    )
  }
}

EditSubApplicationInfo.contextTypes ={
  router: React.PropTypes.object,
};

EditSubApplicationInfo.propTypes = {
  parentMessage: React.PropTypes.any,  //传到父组件
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
  }
}

const WrappedEditSubApplicationInfo = Form.create()(EditSubApplicationInfo);

export default connect(mapStateToProps)(WrappedEditSubApplicationInfo)
